package com.ruicar.afs.cloud.afscase.message.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.admin.api.dto.UserSimpleInfoDto;
import com.ruicar.afs.cloud.afscase.message.entity.CaseNoticeInfo;
import com.ruicar.afs.cloud.afscase.message.mapper.CaseNoticeInfoMapper;
import com.ruicar.afs.cloud.afscase.message.service.CaseNoticeInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ReadEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * <p>Description: </p>
 * 消息通知处理
 * @Author ma_xueyu
 * @Date 2020年8月21日
 */
@Slf4j
@Service
@AllArgsConstructor
public class CaseNoticeInfoServiceImpl extends ServiceImpl<CaseNoticeInfoMapper, CaseNoticeInfo> implements CaseNoticeInfoService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateNoticeInfoBatch(List<CaseNoticeInfo> caseNoticeInfoList, HashSet<UserSimpleInfoDto> receivedByList, ReadEnum readEnum) {
        List<CaseNoticeInfo> caseNoticeInfoBatch=new ArrayList<>();
        receivedByList.forEach(userSimpleInfoDto -> {
            caseNoticeInfoList.forEach(caseNoticeInfo -> {
                CaseNoticeInfo tempNotice=new CaseNoticeInfo();
                tempNotice.setSendBy(caseNoticeInfo.getSendBy());
                tempNotice.setNotice(caseNoticeInfo.getNotice());
                tempNotice.setNoticeType(caseNoticeInfo.getNoticeType());
                tempNotice.setIsRead(AfsEnumUtil.key(readEnum));
                tempNotice.setReceivedBy(userSimpleInfoDto.getUserName());
                caseNoticeInfoBatch.add(tempNotice);
            });
        });
        if (CollectionUtil.isNotEmpty(caseNoticeInfoBatch)&&caseNoticeInfoBatch.size()>0){
            super.saveOrUpdateBatch(caseNoticeInfoBatch,caseNoticeInfoBatch.size());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOutdatedNoticeRead(Enum sysNoticeTypeEnum, Enum readEnum) {
        super.update(Wrappers.<CaseNoticeInfo>lambdaUpdate()
                .eq(CaseNoticeInfo::getNoticeType,AfsEnumUtil.key(sysNoticeTypeEnum))
                .eq(CaseNoticeInfo::getIsRead,AfsEnumUtil.key(ReadEnum.UNREAD))
                .set(CaseNoticeInfo::getIsRead,AfsEnumUtil.key(readEnum)));
    }

}
